package edu.mtu.citizenscience.ethnography.util;


import edu.mtu.citizenscience.ethnography.database.InterviewDataService;
import edu.mtu.citizenscience.ethnography.database.InterviewDataService.InterviewBinder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

public abstract class DataServiceActivity extends EthnographyActivity {
	
	
	
	private static final String LOG_TAG = "DataServiceActivity";
	
	private InterviewDataService dataService = null;
	
	private boolean bound;
	
	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			InterviewBinder binder = (InterviewBinder) service;
			dataService = binder.getService();
			bound = true;
			performDatabaseOperation();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.e(LOG_TAG, "Interview disconnected unexpectedly");
			bound = false;
		}
		
	};
	
	@Override
	protected void onStart() {
		super.onStart();
		bindService(new Intent(this, InterviewDataService.class), connection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		unbindService(connection);
	}
	
	public final InterviewDataService getService() {
		return dataService;
	}
	
	protected final boolean isBound() {
		return bound;
	}
	
	protected abstract void performDatabaseOperation();
}
